﻿using Org.BouncyCastle.Crypto;
using ProTrack.Entity;
using ProTrack.IRepository;
using ProTrack.IServices.Product;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;

namespace ProTrack.Services.Product
{
    public class SpecServices : ISpecServices
    {
        public SpecServices(IBaseRepository db)
        {
            Db = db;
        }

        public IBaseRepository Db { get; }

        public async Task<bool> AddAsync(Spec model)
        {
            var result = await Db.InsertAsync(model);
            return result;
        }

        public async Task<bool> DeleteAsync(int[] Ids)
        {
            string sql = "delete Spec where Id in @Ids";
            var result = await Db.DeleteAsync(sql,new { Ids });
            return result;
        }

        public async Task<bool> DeleteAsync(int Id)
        {
            string sql = "delete Spec where Id =@Id ";
            var result = await Db.DeleteAsync(sql, new { Id });
            return result;
        }

        public async Task<IEnumerable<Spec>> GetAllAsync()
        {
            string sql = "select * from Spec";
            var list = await Db.QueryAllAsync<Spec>(sql);
            return list;
        }


        public async Task<bool> UpdateAsync(Spec model)
        {
            var result = await Db.UpdateAsync(model);
            return result;
        }

        public async Task<IEnumerable<Spec>> GetAsync(int PageIndex, int PageSize, string Model, string Serial, string Name)
        {
            string sql = "select * from Spec where 1=1 ";
            if(!string.IsNullOrEmpty(Model))
            {
                sql += " and Model like @Model ";
            }


            if(!string.IsNullOrEmpty(Serial))
            {
                sql += " and Serial like @Serial ";
            }

            if (!string.IsNullOrEmpty(Name))
            {
                sql += " and Name like @Name ";
            }




            sql += "order by CreateTime desc offset @PageSize*(@PageIndex-1) row fetch next @PageSize rows only";

            var list = await Db.QueryAsync<Spec>(sql, new { PageIndex,PageSize, Model=$"%{Model}%", Serial=$"%{Serial}%", Name = $"%{Name}%" });
            return list;

        }

        public async Task<int> GetCountAsync(string Model, string Serial, string Name)
        {
            string sql = "select count(*) from Spec where 1=1 ";
            if (!string.IsNullOrEmpty(Model))
            {
                sql += " and Model like @Model ";
            }

            if (!string.IsNullOrEmpty(Serial))
            {
                sql += " and Serial like @Serial ";
            }

            if (!string.IsNullOrEmpty(Name))
            {
                sql += " and Name like @Name ";
            }

            var count = await Db.GetRecoreCountAsync(sql, new { Model = $"%{Model}%", Serial = $"%{Serial}%" , Name =$"%{Name}%"});
            return count;
        }

    }
}
